﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using EShop.Core;
using EShop.Core.Caching;
using EShop.Core.Data;
using EShop.Core.Events;
using EShop.Core.Model.Store;

namespace EShop.Services.Store
{
    public class OrderService:IOrderService
    {
        #region Constants
        private const string ORDER_BY_ID_KEY = "EShop.Order.id-{0}";
        private const string ORDERMORE_BY_ID_KEY = "EShop.OrderMore.id-{0}";
        private const string ORDER_PATTERN_KEY = "EShop.Order";
        #endregion

        #region Fields
        private readonly IRepository<Order> _orderRepository;
        private readonly IRepository<OrderMore> _ordermoreRepository;
        private readonly ICacheManager _cacheManager;
        private readonly IEventPublisher _eventPublisher;
        //private readonly IDbContext _context;
        #endregion

        #region Ctor
        public OrderService(IRepository<Order> orderRepository,IRepository<OrderMore> ordermoreRepository, ICacheManager cacheManager, IEventPublisher eventPublisher)
        {
            _orderRepository = orderRepository;
            _ordermoreRepository = ordermoreRepository;
            _cacheManager = cacheManager;
            _eventPublisher = eventPublisher;
        }
        #endregion

        #region Methods

        /// <summary>
        /// 查询定单
        /// </summary>
        /// <param name="start"></param>
        /// <param name="limit"></param>
        /// <param name="fiter"></param>
        /// <returns></returns>
        public IPagedList<Order> GetAllOrder(int pageIndex, int pageSize, int orderState = -1)
        {
            var query = _orderRepository.Table;
            if (orderState!=-1)
                query = query.Where(c => c.State==orderState);
            query = query.OrderBy(c => c.Id);

            return new PagedList<Order>(query, pageIndex, pageSize);

        }
        /// <summary>
        /// 获取一条定单信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Order GetOrderById(int id)
        {
            if (id <= 0)
                return null;
            //格式化缓存条件
            string key = string.Format(ORDER_BY_ID_KEY, id);
            return _cacheManager.Get(key, () =>
            {
                var brand = _orderRepository.GetById(id);
                return brand;
            });
        }

        /// <summary>
        /// 删除定单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool DeleteOrder(int id)
        {
            var model = _orderRepository.GetById(id);
            if (model == null)
                throw new ArgumentNullException("NUll Order Model");

            //标记成删除
            model.State = -1;
            int r = _orderRepository.Update(model);

            if (r > 0)
            {
                //cache
                _cacheManager.RemoveByPattern(ORDER_BY_ID_KEY);

                //event notification
                _eventPublisher.EntityUpdated(model);
            }
            return r > 0 ? true : false;
        }

        /// <summary>
        /// 修改定单
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool UpdateOrder(Order model)
        {

            if (model == null) throw new ExtException("NUll Order Model");

            int rs = _orderRepository.Update(model);
            if (rs > 0)
            {
                //event notification
                _eventPublisher.EntityUpdated(model);

            }
            return rs > 0 ? true : false;
        }
        /// <summary>
        /// 按指定条件查询定单
        /// </summary>
        /// <param name="fiter"></param>
        /// <returns></returns>
        public List<Order> GetAllOrder(int userId, bool showHidden = false)
        {
            var query = _orderRepository.Table;
            if (!showHidden)
                query = query.Where(c => c.State!=-1);

            if (userId > 0) query = query.Where(c => c.Userid == userId);

            var unsortedCategory = query.ToList();

            //sort categories
            return unsortedCategory;
        }
        /// <summary>
        /// 创建定单
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int CreateOrder(Order model)
        {

            if (model == null) throw new ExtException("NUll Order Model");
            //判断订单是否存在
            if (_orderRepository.Table.Where(c => c.OrderNum.ToLower() == model.OrderNum.Trim().ToLower()).Count() > 0) return 3;

            int rs = _orderRepository.Insert(model);
            if (rs > 0)
            {
                rs = 1;
                //event notification
                _eventPublisher.EntityInserted(model);

            }
            return rs;
        }
        /// <summary>
        /// 插入定单
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool CreateOrderMore(OrderMore model)
        {
            bool ret=false;
            #region 判断订单是否存在
           
            #endregion
            return ret;
        }
        /// <summary>
        /// 通过条件获取定单信息
        /// </summary>
        /// <param name="fiter"></param>
        /// <returns></returns>
        public List<Order> GetOrderByFiter(string ordernum)
        {
            var query = _orderRepository.Table;
            if (string.IsNullOrEmpty(ordernum)) return null;
            query = query.Where(c => c.OrderNum == ordernum);
            return query.ToList();
             
        }
        ///// <summary>
        ///// 获得更多定单
        ///// </summary>
        ///// <param name="fiter"></param>
        ///// <returns></returns>
        //public DataTable GetOrderMoreByFiter(string fiter)
        //{

        //    DataTable dt = new DataTable();

        //    Library.SqlProvider.OleDb db = new Library.SqlProvider.OleDb();
        //    string str_sql = "  select  * from [tb_mc_order_more] [tb_mc_product] where tb_mc_order_more.productid=tb_mc_product.id and " + fiter;
        //    try
        //    {

        //        dt = db.ExecuteDataset(COMM.PucConfig.ConnectionStringA, CommandType.Text, str_sql).Tables[0];
        //    }
        //    catch (Exception ex) { }

        //    return dt;
        //}
        /// <summary>
        /// 获取定单详细信息
        /// </summary>
        /// <param name="fiter"></param>
        /// <returns></returns>
        public OrderMore GetOrderMoreById(int id)
        {
            
            if (id <= 0)
                return null;
            //格式化缓存条件
            string key = string.Format(ORDERMORE_BY_ID_KEY, id);
            return _cacheManager.Get(key, () =>
            {
                var brand = _ordermoreRepository.GetById(id);
                return brand;
            });
        }
        /// <summary>
        /// 取得定单号码
        /// </summary>
        /// <returns></returns>
        public string GetOrderNumbernew()
        {

            string tempstr = DateTime.Now.ToString("yyyyMMddhhmmss");
            Random rnd = new Random();
            tempstr = tempstr + rnd.Next(100000).ToString() + rnd.Next(100000, 999999).ToString();
            return tempstr;
        }
        #endregion
    }
}
